package com.kelvem.saas.workbanch.ontology.piaoorder.handle.core;

import com.kelvem.saas.workbanch.fsm.container.DaoContainer;
import com.kelvem.saas.workbanch.fsm.dao.BaseDao;
import com.kelvem.saas.workbanch.fsm.entity.Entity;
import com.kelvem.saas.workbanch.fsm.entity.FsmEntity;
import com.kelvem.saas.workbanch.fsm.entity.FsmHistoryEntity;
import com.kelvem.saas.workbanch.fsm.core.EventContext;
import com.kelvem.saas.workbanch.fsm.handle.Handle;
import com.kelvem.saas.workbanch.fsm.model.EventNode;
import com.kelvem.saas.workbanch.fsm.entity.FsmEventReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author kelvem
 */
@Service
@Slf4j
public class PiaoOrderStateHandle extends Handle {
    
    @Override
    public void execute() {
    
        FsmEventReq req = null;
        if (EventContext.getRequest() instanceof FsmEventReq) {
            req = (FsmEventReq) EventContext.getRequest();
        }
        
        // eventNode
        EventNode eventNode = EventContext.getEventNode();
        String dstState = eventNode.getDstState();
        
        // entity
        FsmEntity entity = Entity.instance().selectOne(eventNode.getEntityClazz());
        if (entity.getState() == null || "".equals(entity.getState())) {
            // todo enum
            entity.setState("start");
        }
        
        // save entity
        BaseDao dao = DaoContainer.getDao(eventNode.getEntityClazz());
        if (entity.getId() == null) {
            dao.insert(entity);
        } else {
            dao.updateById(entity);
        }
        
        // FsmHistoryEntity
        FsmHistoryEntity history = new FsmHistoryEntity();
        history.setSrcState(entity.getState());
        history.setDstState(eventNode.getDstState());
        history.setEventCode(eventNode.getCode());
        history.setEntityType(eventNode.getEntityName());
        history.setEntityId(entity.getId());
        history.setCreateTime(new Date());
        
        if (req != null) {
            history.setMemo(req.getMemo());
            history.setUpdateUid(req.getOptUid());
            history.setUpdateTime(req.getOptTime());
        }
        
        EventContext.addContext(history);
    
        // 修改订单状态
        entity.setState(dstState);
        entity.setStateTime(new Date());
    
        EventContext.print();
    }
}
